<template>
  <view class="detail-container">
    <!-- Loading State -->
    <view class="loading-container" v-if="loading">
      <text>加载中...</text>
    </view>

    <!-- Error State -->
    <view class="error-container" v-if="error && !loading">
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="retryLoad">重试</button>
    </view>

    <!-- Moment Content -->
    <view v-if="!loading && !error && moment">
      <!-- Moment Card -->
      <view class="moment-card">
        <view class="card-header">
          <image class="author-avatar" :src="safeImageUrl(moment.authorAvatar)" mode="aspectFill"></image>
          <view class="author-info">
            <text class="author-name">{{ moment.authorName || '未知用户' }}</text>
            <text class="moment-time">{{ formatTime(moment.createdAt) }}</text>
          </view>
        </view>
        <view class="card-body">
          <text class="moment-content">{{ moment.content }}</text>
          <view v-if="getImages(moment.images).length" class="moment-images">
            <image 
              v-for="(image, index) in getImages(moment.images)" 
              :key="index" 
              class="moment-image" 
              :src="buildImageUrl(image)" 
              mode="aspectFill"
              @error="onImageError"
            ></image>
          </view>
        </view>
        <view class="card-footer">
          <view class="action-item" @click="toggleLike">
            <text class="action-icon" :class="{ 'liked': isLiked }">👍</text>
            <text class="action-text">{{ moment.likeCount || 0 }}</text>
          </view>
          <view class="action-item">
            <text class="action-icon">💬</text>
            <text class="action-text">{{ comments.length }}</text>
          </view>
        </view>
      </view>

      <!-- Comments Section -->
      <view class="comments-container">
        <view class="comments-header">
          <text class="comments-title">评论 ({{ comments.length }})</text>
        </view>
        
        <scroll-view scroll-y class="comments-section" v-if="comments.length > 0">
          <view class="comment-list">
            <view class="comment-item" v-for="comment in comments" :key="comment.id">
              <image class="comment-avatar" :src="safeImageUrl(comment.userAvatar)" mode="aspectFill"></image>
              <view class="comment-content">
                <text class="comment-author">{{ comment.userName || '未知用户' }}</text>
                <text class="comment-text">{{ comment.content }}</text>
                <text class="comment-time">{{ formatTime(comment.createdAt) }}</text>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="empty-comments" v-if="comments.length === 0">
          <text>还没有评论，来发表第一条吧~</text>
        </view>
      </view>
    </view>

    <!-- Comment Input -->
    <view class="comment-input-bar" v-if="!loading && !error">
      <input 
        class="comment-input" 
        v-model="newComment" 
        placeholder="发表你的看法..."
        :disabled="commenting"
      />
      <button 
        class="send-btn" 
        @click="handlePostComment"
        :disabled="!newComment.trim() || commenting"
      >
        {{ commenting ? '发送中...' : '发送' }}
      </button>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import imageHelper from '@/utils/imageHelper';

export default {
  name: 'MomentDetail',
  data() {
    return {
      momentId: null,
      moment: null,
      newComment: '',
      loading: false,
      commenting: false,
      error: null,
      isLiked: false,
      // baseUrl: 'http://localhost:8080' // 已移除
    };
  },
  computed: {
    ...mapState('moments', ['comments']),
  },
  onLoad(options) {
    if (options.moment) {
      // 从列表页传递的完整moment数据
      this.moment = JSON.parse(decodeURIComponent(options.moment));
      this.momentId = this.moment.id;
      this.loadComments();
    } else if (options.id) {
      // 从首页传递的moment id
      this.momentId = parseInt(options.id);
      this.loadMomentAndComments();
    } else {
      this.error = '无效的动态参数';
    }
  },
  methods: {
    ...mapActions('moments', ['fetchComments', 'addComment', 'getMomentDetail', 'likeMoment', 'unlikeMoment']),
    
    async loadMomentAndComments() {
      try {
        this.loading = true;
        this.error = null;
        
        // 加载动态详情
        this.moment = await this.getMomentDetail(this.momentId);
        
        // 加载评论
        await this.loadComments();
      } catch (error) {
        console.error('加载动态详情失败:', error);
        this.error = '加载失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },

    async loadComments() {
      try {
        await this.fetchComments(this.momentId);
      } catch (error) {
        console.error('加载评论失败:', error);
      }
    },

    async retryLoad() {
      if (this.momentId) {
        await this.loadMomentAndComments();
      }
    },

    async handlePostComment() {
      if (!this.newComment.trim()) return;

      try {
        this.commenting = true;
        const commentData = {
          content: this.newComment.trim()
        };
        
        await this.addComment({ momentId: this.momentId, commentData });
        this.newComment = '';
        
        // 刷新评论列表
        await this.loadComments();
        
        uni.showToast({
          title: '评论成功',
          icon: 'success'
        });
      } catch (error) {
        console.error('评论失败:', error);
        uni.showToast({
          title: '评论失败',
          icon: 'none'
        });
      } finally {
        this.commenting = false;
      }
    },

    async toggleLike() {
      try {
        if (this.isLiked) {
          await this.unlikeMoment(this.momentId);
          this.isLiked = false;
        } else {
          await this.likeMoment(this.momentId);
          this.isLiked = true;
        }
        
        // 更新本地数据
        if (this.moment) {
          this.moment.likeCount = (this.moment.likeCount || 0) + (this.isLiked ? 1 : -1);
        }
      } catch (error) {
        console.error('点赞操作失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    },

    formatTime(timeStr) {
      if (!timeStr) return '';
      
      const now = new Date();
      const time = new Date(timeStr);
      const diff = now.getTime() - time.getTime();
      
      if (diff < 60 * 1000) {
        return '刚刚';
      } else if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前';
      } else if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
      } else {
        return time.toLocaleDateString();
      }
    },

    getImages(imagesJson) {
      if (!imagesJson) return [];
      
      try {
        if (typeof imagesJson === 'string') {
          return JSON.parse(imagesJson);
        }
        return Array.isArray(imagesJson) ? imagesJson : [];
      } catch (error) {
        console.error('解析图片数据失败:', error);
        return [];
      }
    },

    buildImageUrl(image) {
      // 直接调用修复后的 imageHelper
      return imageHelper.buildImageUrl(image);
    },

    safeImageUrl(url) {
      // 直接调用修复后的 imageHelper
      return imageHelper.safeImageUrl(url, 'avatar');
    },

    onImageError(e) {
      console.warn('图片加载失败:', e);
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx; /* 为输入框留出空间 */
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 40rpx;
  
  .error-text {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 40rpx;
  }
  
  .retry-btn {
    background: #007AFF;
    color: white;
    padding: 16rpx 32rpx;
    border-radius: 24rpx;
    border: none;
    font-size: 28rpx;
  }
}

.moment-card {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.author-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-right: 24rpx;
}

.author-info {
  flex: 1;
}

.author-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.moment-time {
  font-size: 24rpx;
  color: #666;
}

.card-body {
  margin-bottom: 24rpx;
}

.moment-content {
  font-size: 32rpx;
  line-height: 1.6;
  color: #333;
  display: block;
  margin-bottom: 24rpx;
}

.moment-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12rpx;
}

.moment-image {
  width: 100%;
  height: 200rpx;
  border-radius: 8rpx;
}

.card-footer {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 24rpx;
}

.action-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  padding: 12rpx;
  border-radius: 24rpx;
  
  &:active {
    background: #f0f0f0;
  }
}

.action-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
  
  &.liked {
    color: #007AFF;
  }
}

.action-text {
  font-size: 28rpx;
  color: #666;
}

.comments-container {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.comments-header {
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.comments-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.comments-section {
  max-height: 800rpx;
}

.comment-list {
  padding: 24rpx 32rpx;
}

.comment-item {
  display: flex;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
}

.comment-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-author {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.comment-text {
  font-size: 30rpx;
  line-height: 1.5;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
}

.empty-comments {
  padding: 80rpx 32rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.comment-input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx;
  border-top: 1rpx solid #e0e0e0;
  display: flex;
  align-items: center;
  z-index: 1000;
}

.comment-input {
  flex: 1;
  background: #f5f5f5;
  border-radius: 24rpx;
  padding: 16rpx 24rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  border: none;
  
  &:disabled {
    opacity: 0.6;
  }
}

.send-btn {
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 24rpx;
  padding: 16rpx 32rpx;
  font-size: 28rpx;
  
  &:disabled {
    background: #ccc;
  }
}
</style> 